package com.ynjt.server;

import com.ynjt.model.Message;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

@ChannelHandler.Sharable
public class ChatServerHandler extends SimpleChannelInboundHandler<Message> {

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
        Channel incoming = ctx.channel();
        Message message = new Message(incoming.remoteAddress().toString(),"name",incoming.remoteAddress().toString(), incoming.remoteAddress() + " 加入\n");
        //channels.writeAndFlush("[用户] " + incoming.remoteAddress() + " 加入\n");
        channels.writeAndFlush(message);
        channels.add(ctx.channel());
        System.out.println("用户:" + incoming.remoteAddress() + " 上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception { // (6)
        Channel incoming = ctx.channel();
        System.out.println("用户:" + incoming.remoteAddress() + " 下线");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel incoming = ctx.channel();
        System.out.println("用户:" + incoming.remoteAddress() + " 异常");
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message message) throws Exception {
        System.out.printf("ChatServerHandler  channelRead");
        Channel incoming = ctx.channel();
        for (Channel channel : channels) {
            channel.writeAndFlush(message);
        }
    }
}
